package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    private ThreadPoolExecutor threadPoolExecutor = null;

    private Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();

    private String appBase;

    private int port = 8080;

    public void init(){
        // 加载解析相关的配置，server.xml
        loadServer();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
    }
    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap,appBase);
            threadPoolExecutor.execute(requestProcessor);
        }
    }

    private void loadServer() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        Document document = null;
        try {
            document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            Element serviceElement = (Element)rootElement.selectSingleNode("//Service");//暂时处理一个service的情况
            Element connectorElement = (Element)serviceElement.selectSingleNode("//Connector");
            String portStr = connectorElement.attribute("port").getStringValue();
            port = Integer.parseInt(portStr);
            Element engineElement = (Element)serviceElement.selectSingleNode("//Engine");
            Element hostElement = (Element)engineElement.selectSingleNode("//Host");
            //获取当前service下所有的host配置
            appBase = hostElement.attribute("appBase").getStringValue();
            List<File> webFiles = PubUtils.searchFiles(new File(appBase), "web.xml");
            for (File webFile : webFiles) {
                loadServlet(webFile);
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet(File webFile) {
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = new FileInputStream(webFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();
                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                MyClassLoader myClassLoader = new MyClassLoader();
                servletMap.put("/"+webFile.getParentFile().getName() + urlPattern, myClassLoader.getClassLoadServlet(webFile.getAbsolutePath(),servletClass));
            }
        } catch (DocumentException | ClassNotFoundException | InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.init();
        try {
            bootstrap.start();// 启动Minicat
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
